﻿using System;
using System.Net;
using hStatsC.Helper;
using hStatsC.Models;
using Newtonsoft.Json;

namespace hStatsC.hStatsN
{
    public class hStatsN
    {
        private const string Server = "http://api.heerdev.top:4999";

        public hStatsN(string appid, string version)
        {
            Appid = appid;
            this.Version = version;
            Launch();
        }

        public string Appid { get; private set; }
        public string Version { get; private set; }

        /// <summary>
        /// 检查是否需要更新
        /// </summary>
        /// <returns></returns>
        public bool CheckUpdate(out AppVersion version)
        {
            try
            {
                var url = $"{Server}/AppVersions/Latest?appid={Appid}";
                var v = JsonConvert.DeserializeObject<AppVersion>(HttpHelper.Get(url));
                version = v;
                if (v.Version != this.Version)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                version = null;
                return false;
            }
        }

        public bool CheckUpdate()
        {
            return CheckUpdate(out var version);
        }

        private void Launch()
        {
            try
            {
                HttpHelper.Get($"{Server}/AppLaunchTimes/Add/?appid={this.Appid}");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
    }
}